#!/user/bin/env python
# -*- coding: UTF-8 -*-
# Author: xieyuheng
# Date: 2024/2/26
"""
该文件用于 单例模式实例化驱动
"""
import pyautogui

from common.soft_operate import *
from utils.utils_log import loggerCase
import uiautomation as auto
from common_ai_img.env import ai_object_detect_env

class Browser(object):
    """实例化驱动"""
    driver = None
    instance = False
    app_name = readconfig.app_name

    def __new__(cls, *args, **kwargs):
        """
        获取驱动
        :param args:
        :param kwargs:
        :return: 返回实例
        """
        if cls.driver is None:
            if readconfig.is_need_relaunch:
                loggerCase.info("开始杀死软件")
                close_app_kill()
                cls.driver = None
            if cls.driver is None:
                loggerCase.info("实例化驱动")
                #modify_file_configuration()
                Browser.get_or_launch_driver()
                Browser.input_username_and_password()
                cls.instance = object.__new__(cls)
        return cls.instance

    @staticmethod
    def get_or_launch_driver():
        #实例化驱动，并查找窗口是否存在
        driver = auto.WindowControl(Name=Browser.app_name)

        if driver.Exists():
            driver.SetActive()
        else:
            #窗口不存在，则启动软件
            launch_app()
            Browser.wait_for_window()
            driver.SetActive()
        ai_object_detect_env.PRODUCTLINE = "InnovativeProducts"
        ai_object_detect_env.SOFTWARE = "FS7"
        ai_object_detect_env.SOFTWARE_WIN_ALIAS = Browser.app_name
        ai_object_detect_env.LANGUAGE = "English"
        ai_object_detect_env.WINDOWS_TO_TOP = True
        # ai_object_detect_env.TSFOLDER = "软件ts文件夹"
        # ai_object_detect_env.OUTPUT_DIR = "运行过程中图片的存储路径"
        # ai_object_detect_env.MOUSE_RESET = True
        return driver

    @staticmethod
    def wait_for_window(timeout=60, interval=0.5):
        start_time = time.time()
        while time.time() - start_time < timeout:
            try:
                window = auto.WindowControl(searchDepth=1, Name=Browser.app_name)
                if window.Exists():
                    return
            except:
                pass
                time.sleep(interval)
                loggerCase.info(f"窗口 '{Browser.app_name}' 在 {timeout} 秒内未出现。")
                raise Exception(f"窗口 '{Browser.app_name}' 在 {timeout} 秒内未出现。")

    @staticmethod
    def input_username_and_password():
        loggerCase.debug("登陆通行证")
        auto.EditControl(foundIndex=2).SendKeys(str(readconfig.enter_pass_user))
        auto.EditControl(foundIndex=3).SendKeys(readconfig.enter_pass_password)
        pyautogui.press("enter")

if __name__ == '__main__':
    Browser()




